//
//  OAuthViewController.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/11/18.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 通过webView加载微博授权界面
class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        //设置代理
        webView.delegate = self
        //设置导航栏
        title = "微博登录"
        //设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBackButton: true)
        //自动填充
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //加载授权界面
        加载授权页面()
    }
    /// 关闭页面
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    /// 自动填充用户名和密码
    @objc private func autoFill() {
        //准备js让webView执行
        let jsString = "document.getElementById('userId').value = '276675358@qq.com';" + "document.getElementById('passwd').value = 'meng1130uitf';"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
    //MARK: - 加载授权页面
    private func 加载授权页面() {
        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        printLog(message: urlString)
        //1> URL确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        //2> 建立请求
        let request = URLRequest(url: url)
        //3> 加载请求
        webView.loadRequest(request)
    }
}
extension OAuthViewController: UIWebViewDelegate {
    
    /// 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载  request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 确认思路
        // 1.如果请求地址包含 http://www.baidu.com 则不加载
        if request.url?.absoluteString.hasPrefix(redirectUri) == false {
            return true
        }
//        printLog(message: "加载的url\(request.url?.absoluteString)")
//        // query就是url?后面的部分
//        printLog(message: request.url?.query)
        
        // 2.在包含 http://www.baidu.com 的地址中查询 'code='
        // 如果有则授权成功,否则授权失败
        if request.url?.query?.hasPrefix("code=") == false  {
            printLog(message: "取消授权")
            close()
            return false
        }
        //3.从query字符串中取出授权码,代码走到此处一定有code=
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        printLog(message: "授权码\(code)")
        
        NetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录失败");
            } else {
                // 跳转界面
                //1. 发送通知页面刷,不管是否有监听者
                NotificationCenter.default.post(name: NSNotification.Name(userLoginSuccessNotification), object: nil)
                    
                
                //2. 关闭视图
                self.close()
                
            }
        }
        
        SVProgressHUD.dismiss()
        return false
    }
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}




